<template>
  <div>
    <!-- Navbar -->
    <navBar :title="title"></navBar>
    <!-- 内容 -->
    <div class="main">
      <!-- 图文问诊 =》 选择患者 -->
      <div class="select" v-if="isChange">
        <div>请选择患者信息</div>
        <div class="private">以便医生给出更准确的治疗，信息仅医生可见</div>
      </div>
      <!-- 患者信息 -->
      <div
        class="info item"
        :class="{ active: currentId === item.id && isChange }"
        v-for="item in patientList"
        :key="item.id"
        @click="currentId = item.id"
      >
        <div class="left">
          <div class="top">
            <span class="name">{{ item.name }}</span>
            <span class="idNumber"
              >{{ item.idCard.substr(0, 6) }}******{{
                item.idCard.substr(-4)
              }}</span
            >
            <van-tag
              v-if="item.defaultFlag === 1"
              class="default"
              color="#16c2a3"
              >默认</van-tag
            >
          </div>
          <div class="bottom">
            <span>{{ item.genderValue }}</span>
            <span class="age">{{ item.age }}岁</span>
          </div>
        </div>
        <img
          v-if="currentId === item.id && isChange"
          class="edit"
          src="@/assets/upload/edit-active@2x.png"
          @click="onEdit(item)"
        />
        <img
        v-else
          class="edit"
          src="@/assets/upload/edit-default@2x.png"
          @click="onEdit(item)"
        />
      </div>
      <!-- 添加患者 -->
      <div class="info add" @click="isShow = true">
        <van-icon name="plus" class="icon" />
        <div>添加患者</div>
      </div>
      <div>最多可添加 6 人</div>
    </div>
    <!-- 下一步按钮 -->
    <div class="next" v-if="isChange">
      <van-button color="#16c2a3" block round @click="$router.push(`/consult/pay/${currentId}`)">
        下一步
      </van-button>
    </div>

    <!-- 弹出层 -->
    <van-popup
      v-model:show="isShow"
      position="right"
      :style="{ width: '100%', height: '100%' }"
    >
      <template #default>
        <van-nav-bar :title="popupTitle" left-arrow @click-left="onIsShow">
          <template #right>
            <button class="save" type="submit" @click="onSubmit">保存</button>
          </template>
        </van-nav-bar>
        <van-form ref="target" @submit="submit" validate-trigger="onSubmit">
          <van-field
            v-model.trim="popupForm.name"
            name="name"
            label="真实姓名"
            placeholder="请输入真实姓名"
            :rules="rules.name"
          />
          <van-field
            v-model.trim="popupForm.idCard"
            name="idCard"
            label="身份证号"
            placeholder="请输入身份证号"
            :rules="rules.idCard"
          />
          <van-field name="gender" label="性别">
            <template #input>
              <van-button
                class="gender"
                :class="{ active: popupForm.gender === 1 }"
                @click="popupForm.gender = 1"
                >男</van-button
              >
              <van-button
                class="gender"
                :class="{ active: popupForm.gender === 0 }"
                @click="popupForm.gender = 0"
                >女</van-button
              >
            </template>
          </van-field>
          <van-field name="defaultFlag" label="默认就诊人">
            <template #input>
              <van-checkbox v-model="popupForm.defaultFlag" />
            </template>
          </van-field>
        </van-form>
        <!-- 底部删除按钮 -->
        <div class="footer" v-if="popupForm.id">
          <van-button class="delete" @click="onDel(popupForm)">删除</van-button>
        </div>
      </template>
    </van-popup>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { showToast, showConfirmDialog, showSuccessToast } from 'vant'
import { getPatientList, addPatient, editPatient, delPatient } from '@/api'
import { useRoute } from 'vue-router'

const route = useRoute()
const isChange = route.query.isChange

// navbar title
const title = isChange ? '选择患者' : '家庭档案'

// 当前高亮的项
const currentId = ref('')

// 获取患者列表信息
const patientList = ref([])
const fetchPatientList = async () => {
  const { data } = await getPatientList()
  patientList.value = data
  currentId.value = data[0].id
}
fetchPatientList()

// 弹出层
const isShow = ref(false)

// 关闭弹出层
const onIsShow = () => {
  isShow.value = false
  popupForm.value = {
    name: '',
    idCard: '',
    gender: 1,
    defaultFlag: false
  }
  popupTitle.value = '添加患者'
}

// 弹出层表单数据
const popupForm = ref({
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: false
})

// 弹出层标题
const popupTitle = ref('添加患者')

// 校验函数可以直接返回一段错误提示
const nameMessage = () => {
  showToast('请输入真实姓名')
}
const idCardMessage = () => {
  showToast('请输入身份证号')
}
const formatMessage = () => {
  showToast('身份证格式错误')
}
// 校验函数返回 true 表示校验通过，false 表示不通过
const validator = (val) => {
  console.log(val.substr(16, 1))
  if (popupForm.value.gender === 0) {
    return val.substr(16, 1) % 2 === 0
  } else {
    return val.substr(16, 1) % 2 !== 0
  }
}
const genderMessage = () => {
  showToast('性别和身份证不符')
}

// 校验规则
const rules = {
  name: [{ required: true, message: nameMessage }],
  idCard: [
    { required: true, message: idCardMessage },
    {
      pattern:
        /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/,
      message: formatMessage
    },
    { validator, message: genderMessage }
  ]
}

// 保存
const target = ref(null)
const onSubmit = () => {
  target.value.submit()
}
const submit = async () => {
  popupForm.value.defaultFlag = popupForm.value.defaultFlag ? 1 : 0
  let res = {}
  if (popupForm.value.id) {
    // 编辑
    delete popupForm.value.age
    delete popupForm.value.genderValue
    res = await editPatient(popupForm.value)
  } else {
    // 新增
    res = await addPatient(popupForm.value)
  }
  if (res.data) {
    fetchPatientList()
    onIsShow()
  } else {
    showToast(res.message)
  }
}

// 编辑
const onEdit = (item) => {
  popupForm.value = item
  popupTitle.value = '编辑患者'
  isShow.value = true
}

// 删除
const onDel = (item) => {
  showConfirmDialog({
    title: '温馨提示',
    message: `您确认要删除 ${item.name} 患者信息吗?`
  })
    .then(async () => {
      await delPatient(item.id)
      fetchPatientList()
      showSuccessToast('删除成功')
      onIsShow()
    })
    .catch(() => {
      // on cancel
    })
}
</script>

<style lang="scss" scoped>
::v-deep .van-nav-bar__content {
  .van-icon {
    color: #121826;
  }
  .van-nav-bar__title {
    font-weight: 400;
  }
  .save {
    border: 0;
    background-color: unset;
    color: #16c2a3;
    font-size: 30px;
  }
}

// 内容
.main {
  padding: 30px;
  margin-top: 90px;
  margin-bottom: 180px;
  font-size: 29px;
  color: #848484;
  .select {
    margin-bottom: 60px;
    font-size: 34px;
    color: #121826;
    .private {
      margin-top: 10px;
      font-size: 28px;
      color: #6f6f6f;
    }
  }
  .info {
    margin-bottom: 25px;
    height: 180px;
    border-radius: 10px;
    border: 1px solid #f6f7f9;
    background-color: #f6f7f9;
  }
  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30px;
    .left {
      font-size: 32px;
      color: #121826;
      .top {
        display: flex;
        align-items: center;
        .name {
          width: 200px;
        }
        .idNumber {
          margin-right: 60px;
          font-size: 28px;
        }
        .default {
          font-size: 20px;
        }
      }
      .bottom {
        margin-top: 26px;
        font-size: 28px;
        color: #c3c3c5;
        .age {
          margin-left: 40px;
        }
      }
    }
    .edit {
      width: 30px;
      height: 30px;
    }
  }
  .add {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #16c2a3;
    .icon {
      margin-bottom: 10px;
      font-size: 42px;
    }
  }
}

// 下一步按钮
.next {
  position: fixed;
  left: 0;
  bottom: 0;
  padding: 30px;
  width: 100%;
  background-color: #fff;
}

// 弹出层
.gender {
  margin-right: 20px;
  padding: 0 46px;
  border: 0;
  height: 70px;
  background-color: #f6f7f9;
}
.active {
  border: 1px solid #16c2a3 !important;
  background-color: #eaf8f6 !important;
}
::v-deep .van-checkbox__icon--checked {
  .van-icon {
    background-color: #16c2a3;
    border-color: unset;
  }
}
.footer {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  padding: 30px;
}
.delete {
  border: 0;
  border-radius: 40px;
  width: 100%;
  height: 80px;
  background-color: #f6f7f9;
  color: #eb5757;
  outline: none;
}
</style>
